#include "Button.hpp"

namespace rgui
{

Button::Button(const rgui::vec2f &position, const rgui::vec2f &size, const rgui::Colorf &color, const std::wstring &text) : RenderObject(),
	mRectangle(position, size),
	mText(text, rgui::vec2f(position.x + size.x * 0.5f, position.y + size.y * 0.5f)),
	mColor(color),
	mMouseInside(false)
{
	mText.setAlignment(rgui::Text::AlignmentX::CENTER, rgui::Text::AlignmentY::CENTER);
}

const rgui::Colorf& Button::getColor()
{
	return mColor;
}

void Button::setColor(const rgui::Colorf &color)
{
	mColor = color;
}

void Button::onMousePressed(const rgui::vec2i &cursorPosition)
{
	if(mMouseInside)
	{
		RenderObject::setLastSelected(this);
		onPressed();
	}
}

void Button::onMouseReleased(const rgui::vec2i &cursorPosition)
{
	if(mMouseInside)
	{
		onReleased();
		if(RenderObject::getLastSelected() == this)
		{
			RenderObject::setLastSelected(nullptr);
			onClick(cursorPosition);
		}
	}
	else
	{
		if(RenderObject::getLastSelected() == this)
			RenderObject::setLastSelected(nullptr);
	}
}

void Button::update(const rgui::vec2i &cursorPosition)
{
	bool contains = mRectangle.contains(rgui::vec2f(cursorPosition.x, cursorPosition.y));
	if(!mMouseInside && contains)
	{
		mMouseInside = true;
		mouseEnter();
	}
	else if(mMouseInside && !contains)
	{
		mMouseInside = false;
		mouseLeave();
	}
}

}